package com.example.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Slf4j
@Component
public class CustomPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> tableNames, PreciseShardingValue<Long> shardingValue) {
        if (CollectionUtils.isNotEmpty(tableNames) && shardingValue != null && shardingValue.getValue() != null) {
            try {
                long value = shardingValue.getValue();
                int tableNum = Integer.parseInt(String.valueOf(value).substring(6, 8));
                if (tableNum == 12) {
                    tableNum = tableNum - 1;
                }
                for (String tableName : tableNames) {
                    if (tableName.endsWith(String.valueOf(tableNum))) {
                        return tableName;
                    }
                }
            } catch (Exception e) {
                log.error("找表分片异常!");
            }
        }
        return null;
    }

}
